package eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty;

import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.CodeMismatchException;
import eu.jpereira.trainings.designpatterns.structural.adapter.exceptions.IncorrectDoorCodeException;
import eu.jpereira.trainings.designpatterns.structural.adapter.model.Door;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.DoorState;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.ThirdPartyDoor.LockStatus;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeCodeForUnlockedDoor;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotChangeStateOfLockedDoor;
import eu.jpereira.trainings.designpatterns.structural.adapter.thirdparty.exceptions.CannotUnlockDoorException;

public class ThirdPartyDoorAdapter extends ThirdPartyDoor implements Door {


	private boolean open = false;
	private String code = DEFAULT_CODE;
	
	public ThirdPartyDoorAdapter() {
		// TODO Auto-generated constructor stub
	}

	@Override
	public void open(String code) throws IncorrectDoorCodeException {
		// TODO Auto-generated method stub
		try {
			this.unlock(code);
			try {
				this.setState(DoorState.OPEN);
				this.open = true;
			} catch (CannotChangeStateOfLockedDoor e) {
				// TODO Auto-generated catch block
				//e.printStackTrace();
			}
		} catch (CannotUnlockDoorException e) {
			throw new IncorrectDoorCodeException();
			// TODO Auto-generated catch block
			//e.printStackTrace();
		}
		
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub
		this.lock();
		this.open = false;
	}

	@Override
	public boolean isOpen() {
		// TODO Auto-generated method stub
		//return false;
		return this.open;
	}

	@Override
	public void changeCode(String oldCode, String newCode, String newCodeConfirmation)
			throws IncorrectDoorCodeException, CodeMismatchException {
		// TODO Auto-generated method stub
		if (newCode.equals(newCodeConfirmation)) {
			if (oldCode.equals(this.getString())) {
				 try {
					 open(oldCode);
					 this.setNewLockCode(newCode);
				} catch (CannotChangeCodeForUnlockedDoor e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} else {
				throw new IncorrectDoorCodeException();
			}
		} else {
			throw new CodeMismatchException();
		}
		
	}

	@Override
	public boolean testCode(String code) {
		boolean testCode = false;
		testCode = code.equals(this.getString());
		return testCode;
		//return false;
	}

}
